import { DB_CLOSE_TIMEOUT, DB_NAME, DB_PATH } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/config/dbconfig';
import { closeSqlite } from '@/uni_modules/stars-UniTS-SQLite-ORM/components/stars-UniTS-SQLite-ORM/dbOrm/db/SqliteHelper';

// 退出应用处理
export function setupBackButtonHandler() {
	let backButtonPress = false;
	let firstBackPress = 0;
	if (plus.os.name === 'Android') {
		plus.key.addEventListener('backbutton', () => {
			const currentTime = new Date().getTime();
			if (backButtonPress && (currentTime - firstBackPress < 1000)) {
				// 触发应用关闭回调
				onAppQuit();
				// 延迟一段时间再退出应用，默认：200毫秒，确保回调执行
				setTimeout(() => {
					plus.runtime.quit();
				}, DB_CLOSE_TIMEOUT ? DB_CLOSE_TIMEOUT : 200);
			} else {
				backButtonPress = true;
				firstBackPress = currentTime;
				// 提示用户再次点击返回键退出
				uni.showToast({
					title: '再按一次退出应用00',
					icon: 'none',
					duration: 1000
				});
				// 设置一个定时器，1秒后重置 backButtonPress 状态
				setTimeout(() => {
					backButtonPress = false;
				}, 1000);
			}
		});
	}
}
/**
 * APP退出处理
 * @param {string} dbName 
 * @return 
 */
function onAppQuit() : void {
	try {
		// 关闭数据库
		closeSqlite(DB_NAME, DB_PATH);
		console.log("关闭数据库");
	} catch (error) {
		console.error('Failed to close database:', error);
	}
}